'use client';

/**
 * Project Settings Page
 *
 * Configuration page for project-level settings including:
 * - Basic info (name, description)
 * - Autonomy level
 * - Repository integration
 * - Danger zone (archive, delete)
 *
 * @module app/[locale]/(authenticated)/projects/[id]/settings/page
 */

import { use, useState, useCallback } from 'react';
import { useRouter } from '@/lib/i18n/routing';
import { ArrowLeft, Save, Trash2, Archive, AlertTriangle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { toast } from 'sonner';

interface ProjectSettingsPageProps {
  params: Promise<{
    locale: string;
    id: string;
  }>;
}

// Mock project data - will be replaced with API calls
const mockProject = {
  id: 'proj-001',
  name: 'E-Commerce Platform Redesign',
  slug: 'ecommerce-redesign',
  description: 'Complete redesign of the e-commerce platform with modern UI/UX',
  autonomy_level: 'milestone',
  repository_url: 'https://github.com/example/ecommerce',
  status: 'active',
};

export default function ProjectSettingsPage({ params }: ProjectSettingsPageProps) {
  const { id: projectId } = use(params);
  const router = useRouter();

  // Form state
  const [name, setName] = useState(mockProject.name);
  const [description, setDescription] = useState(mockProject.description);
  const [autonomyLevel, setAutonomyLevel] = useState(mockProject.autonomy_level);
  const [repositoryUrl, setRepositoryUrl] = useState(mockProject.repository_url);
  const [isSaving, setIsSaving] = useState(false);

  const handleBack = useCallback(() => {
    router.push(`/projects/${projectId}`);
  }, [router, projectId]);

  const handleSave = useCallback(async () => {
    setIsSaving(true);
    // TODO: Call API to update project
    await new Promise((resolve) => setTimeout(resolve, 1000));
    toast.success('Settings saved', {
      description: 'Project settings have been updated successfully.',
    });
    setIsSaving(false);
  }, []);

  const handleArchive = useCallback(() => {
    // TODO: Call API to archive project
    toast.info('Project archived', {
      description: 'The project has been archived and is no longer active.',
    });
    router.push('/projects');
  }, [router]);

  const handleDelete = useCallback(() => {
    // TODO: Call API to delete project
    toast.success('Project deleted', {
      description: 'The project has been permanently deleted.',
    });
    router.push('/projects');
  }, [router]);

  return (
    <div className="container mx-auto px-4 py-6">
      <div className="mx-auto max-w-2xl space-y-6">
        {/* Header */}
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={handleBack}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold">Project Settings</h1>
            <p className="text-muted-foreground">Configure project preferences and integrations</p>
          </div>
        </div>

        {/* General Settings */}
        <Card>
          <CardHeader>
            <CardTitle>General</CardTitle>
            <CardDescription>Basic project information and configuration</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="name">Project Name</Label>
              <Input
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Enter project name"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">Description</Label>
              <Textarea
                id="description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Describe your project"
                rows={3}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="repository">Repository URL</Label>
              <Input
                id="repository"
                type="url"
                value={repositoryUrl}
                onChange={(e) => setRepositoryUrl(e.target.value)}
                placeholder="https://github.com/..."
              />
              <p className="text-xs text-muted-foreground">
                Link to the project&apos;s Git repository for code integration
              </p>
            </div>
          </CardContent>
        </Card>

        {/* Autonomy Settings */}
        <Card>
          <CardHeader>
            <CardTitle>Autonomy Level</CardTitle>
            <CardDescription>
              Control how much oversight you want over agent actions
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="autonomy">Agent Autonomy</Label>
              <Select value={autonomyLevel} onValueChange={setAutonomyLevel}>
                <SelectTrigger id="autonomy">
                  <SelectValue placeholder="Select autonomy level" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="full_control">
                    <div className="flex flex-col">
                      <span className="font-medium">Full Control</span>
                      <span className="text-xs text-muted-foreground">
                        Approve every agent action
                      </span>
                    </div>
                  </SelectItem>
                  <SelectItem value="milestone">
                    <div className="flex flex-col">
                      <span className="font-medium">Milestone</span>
                      <span className="text-xs text-muted-foreground">
                        Approve at sprint boundaries
                      </span>
                    </div>
                  </SelectItem>
                  <SelectItem value="autonomous">
                    <div className="flex flex-col">
                      <span className="font-medium">Autonomous</span>
                      <span className="text-xs text-muted-foreground">
                        Only major decisions need approval
                      </span>
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* Save Button */}
        <div className="flex justify-end">
          <Button onClick={handleSave} disabled={isSaving}>
            <Save className="mr-2 h-4 w-4" aria-hidden="true" />
            {isSaving ? 'Saving...' : 'Save Changes'}
          </Button>
        </div>

        <Separator />

        {/* Danger Zone */}
        <Card className="border-destructive/50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-destructive">
              <AlertTriangle className="h-5 w-5" />
              Danger Zone
            </CardTitle>
            <CardDescription>Irreversible actions for this project</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Archive */}
            <div className="flex items-center justify-between rounded-lg border p-4">
              <div>
                <h4 className="font-medium">Archive Project</h4>
                <p className="text-sm text-muted-foreground">
                  Archive this project and stop all agent activity
                </p>
              </div>
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button variant="outline">
                    <Archive className="mr-2 h-4 w-4" aria-hidden="true" />
                    Archive
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Archive Project?</AlertDialogTitle>
                    <AlertDialogDescription>
                      This will stop all agent activity and mark the project as archived. You can
                      unarchive it later if needed.
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction onClick={handleArchive}>Archive Project</AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>

            {/* Delete */}
            <div className="flex items-center justify-between rounded-lg border border-destructive/50 p-4">
              <div>
                <h4 className="font-medium text-destructive">Delete Project</h4>
                <p className="text-sm text-muted-foreground">
                  Permanently delete this project and all its data
                </p>
              </div>
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button variant="destructive">
                    <Trash2 className="mr-2 h-4 w-4" aria-hidden="true" />
                    Delete
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Delete Project?</AlertDialogTitle>
                    <AlertDialogDescription>
                      This action cannot be undone. This will permanently delete the project, all
                      agents, issues, sprints, and activity history.
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction
                      onClick={handleDelete}
                      className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                    >
                      Delete Project
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
