"use client";

import { useState, useEffect } from "react";
import type { Personality } from "@mosaic/shared";
import { PersonalityPreview } from "@/components/personalities/PersonalityPreview";
import type { PersonalityFormData } from "@/components/personalities/PersonalityForm";
import { PersonalityForm } from "@/components/personalities/PersonalityForm";
import {
  fetchPersonalities,
  createPersonality,
  updatePersonality,
  deletePersonality,
} from "@/lib/api/personalities";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Plus, Pencil, Trash2, Eye } from "lucide-react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

export default function PersonalitiesPage(): React.ReactElement {
  const [personalities, setPersonalities] = useState<Personality[]>([]);
  const [selectedPersonality, setSelectedPersonality] = useState<Personality | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [mode, setMode] = useState<"list" | "create" | "edit" | "preview">("list");
  const [deleteTarget, setDeleteTarget] = useState<Personality | null>(null);

  useEffect(() => {
    void loadPersonalities();
  }, []);

  async function loadPersonalities(): Promise<void> {
    try {
      setIsLoading(true);
      const response = await fetchPersonalities();
      setPersonalities(response.data);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load personalities");
    } finally {
      setIsLoading(false);
    }
  }

  async function handleCreate(data: PersonalityFormData): Promise<void> {
    try {
      await createPersonality(data);
      await loadPersonalities();
      setMode("list");
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to create personality");
      throw err;
    }
  }

  async function handleUpdate(data: PersonalityFormData): Promise<void> {
    if (!selectedPersonality) return;
    try {
      await updatePersonality(selectedPersonality.id, data);
      await loadPersonalities();
      setMode("list");
      setSelectedPersonality(null);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to update personality");
      throw err;
    }
  }

  async function confirmDelete(): Promise<void> {
    if (!deleteTarget) return;
    try {
      await deletePersonality(deleteTarget.id);
      await loadPersonalities();
      setDeleteTarget(null);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to delete personality");
    }
  }

  if (mode === "create") {
    return (
      <div className="max-w-4xl mx-auto p-6">
        <PersonalityForm
          onSubmit={handleCreate}
          onCancel={() => {
            setMode("list");
          }}
        />
      </div>
    );
  }

  if (mode === "edit" && selectedPersonality) {
    return (
      <div className="max-w-4xl mx-auto p-6">
        <PersonalityForm
          personality={selectedPersonality}
          onSubmit={handleUpdate}
          onCancel={() => {
            setMode("list");
            setSelectedPersonality(null);
          }}
        />
      </div>
    );
  }

  if (mode === "preview" && selectedPersonality) {
    return (
      <div className="max-w-4xl mx-auto p-6">
        <div className="mb-4">
          <Button
            variant="outline"
            onClick={() => {
              setMode("list");
              setSelectedPersonality(null);
            }}
          >
            ← Back to List
          </Button>
        </div>
        <PersonalityPreview personality={selectedPersonality} />
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto p-6">
      {/* Header */}
      <div className="mb-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">AI Personalities</h1>
            <p className="text-muted-foreground mt-1">
              Customize how the AI assistant communicates and responds
            </p>
          </div>
          <Button
            onClick={() => {
              setMode("create");
            }}
          >
            <Plus className="mr-2 h-4 w-4" />
            New Personality
          </Button>
        </div>
      </div>

      {/* Error Display */}
      {error && (
        <div className="mb-4 p-4 bg-destructive/10 text-destructive rounded-md">{error}</div>
      )}

      {/* Loading State */}
      {isLoading ? (
        <div className="text-center py-12">
          <p className="text-muted-foreground">Loading personalities...</p>
        </div>
      ) : personalities.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <p className="text-muted-foreground mb-4">No personalities found</p>
            <Button
              onClick={() => {
                setMode("create");
              }}
            >
              <Plus className="mr-2 h-4 w-4" />
              Create First Personality
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4">
          {personalities.map((personality) => (
            <Card key={personality.id}>
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="flex items-center gap-2">
                      {personality.name}
                      {personality.isDefault && <Badge variant="secondary">Default</Badge>}
                      {!personality.isActive && <Badge variant="outline">Inactive</Badge>}
                    </CardTitle>
                    <CardDescription>{personality.description}</CardDescription>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => {
                        setSelectedPersonality(personality);
                        setMode("preview");
                      }}
                    >
                      <Eye className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => {
                        setSelectedPersonality(personality);
                        setMode("edit");
                      }}
                    >
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => {
                        setDeleteTarget(personality);
                      }}
                    >
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="flex gap-4 text-sm">
                  <div>
                    <span className="text-muted-foreground">Tone:</span>
                    <Badge variant="outline" className="ml-2">
                      {personality.tone}
                    </Badge>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Formality:</span>
                    <Badge variant="outline" className="ml-2">
                      {personality.formalityLevel.replace(/_/g, " ")}
                    </Badge>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Delete Confirmation Dialog */}
      <AlertDialog
        open={!!deleteTarget}
        onOpenChange={(open) => {
          if (!open) setDeleteTarget(null);
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Personality</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete "{deleteTarget?.name}"? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete}>Delete</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
