"use client";

import { useState } from "react";
import { Plus } from "lucide-react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
} from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { ProviderList } from "@/components/features/settings/provider-list";
import { ProviderSelector } from "@/components/features/settings/provider-selector";
import { ProviderForm } from "@/components/features/settings/provider-form";
import { useSavedProviders } from "@/store/use-settings";
import { ProviderManagementService } from "@/services/provider-management-service";
import { toast } from "@/hooks/use-toast";
import { ThemeToggle } from "@/components/features/settings/theme-toggle";
import { AppHeader } from "@/components/layout";

export default function SettingsPage() {
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [editingProviderId, setEditingProviderId] = useState<string | null>(null);
  const providers = useSavedProviders();

  const handleEditProvider = (id: string) => {
    setEditingProviderId(id);
  };

  const handleDeleteProvider = (id: string) => {
    if (confirm("Are you sure you want to delete this provider?")) {
      ProviderManagementService.removeProviderProfile(id);
      toast({
        title: "Provider Deleted",
        description: "The provider has been removed.",
      });
    }
  };

  const closeDialogs = () => {
    setIsAddDialogOpen(false);
    setEditingProviderId(null);
  };

  // Find the provider object being edited
  const editingProvider = providers.find((p) => p.id === editingProviderId);

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <AppHeader />

      {/* Main Content */}
      <div className="py-8 sm:py-12 px-4 sm:px-6 lg:px-8 w-full">
        <div className="max-w-2xl mx-auto space-y-8 sm:space-y-10">

          {/* Page Title */}
          <div>
            <h1 className="text-4xl font-bold tracking-tight text-foreground font-serif">Settings</h1>
            <p className="mt-2 text-lg text-muted-foreground">
              Manage your AI provider connections and preferences.
            </p>
          </div>

          <div className="grid gap-8">
            {/* General Settings */}
            <section className="space-y-4">
              <div className="flex items-center gap-2 pb-2 border-b border-border">
                <div className="h-8 w-1 bg-yellow-400 rounded-full"></div>
                <h2 className="text-xl font-semibold text-foreground font-serif">Appearance</h2>
              </div>
              <div className="flex items-center justify-between">
                <p className="text-sm text-muted-foreground max-w-xl">
                  Choose your preferred theme for the journaling experience.
                </p>
                <ThemeToggle />
              </div>
            </section>

            {/* Active Provider Section */}
            <section className="space-y-4">
              <div className="flex items-center gap-2 pb-2 border-b border-border">
                <div className="h-8 w-1 bg-primary rounded-full"></div>
                <h2 className="text-xl font-semibold text-foreground font-serif">Active Session Provider</h2>
              </div>
              <p className="text-sm text-muted-foreground max-w-xl">
                Select which AI provider handles your current venting session. This setting applies immediately to new messages.
              </p>
              <ProviderSelector />
            </section>

            {/* Manage Providers Section */}
            <section className="space-y-6">
              <div className="flex items-center justify-between pb-2 border-b border-border">
                <div className="flex items-center gap-2">
                  <div className="h-8 w-1 bg-slate-300 dark:bg-slate-700 rounded-full"></div>
                  <h2 className="text-xl font-semibold text-foreground font-serif">Configuration</h2>
                </div>
              </div>

              <div className="space-y-4">
                <p className="text-sm text-muted-foreground max-w-xl">
                  Configure connection details for your AI models. Keys are stored locally in your browser.
                </p>
                <ProviderList
                  onEditProvider={handleEditProvider}
                  onDeleteProvider={handleDeleteProvider}
                  onAddProvider={() => setIsAddDialogOpen(true)}
                />
              </div>

              {/* Add Provider Dialog (Triggered by ProviderList) */}
              <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
                <DialogContent className="sm:max-w-[550px] p-0 overflow-hidden bg-background border-border shadow-2xl">
                  <DialogHeader className="p-6 pb-2 bg-muted/50">
                    <DialogTitle className="text-2xl font-serif text-foreground">Add New Provider</DialogTitle>
                  </DialogHeader>
                  <div className="p-6 pt-2">
                    <ProviderForm
                      mode="add"
                      onSave={() => {
                        closeDialogs();
                      }}
                      onCancel={closeDialogs}
                    />
                  </div>
                </DialogContent>
              </Dialog>
            </section>
          </div>

          {/* Account Security Section */}
          <div className="grid gap-8 mt-10 border-t border-border pt-10">
            <section className="space-y-4">
              <div className="flex items-center gap-2 pb-2 border-b border-border">
                <div className="h-8 w-1 bg-red-400 rounded-full"></div>
                <h2 className="text-xl font-semibold text-foreground font-serif">Account Security</h2>
              </div>
              <p className="text-sm text-muted-foreground max-w-xl">
                Lock the application to prevent unauthorized access on this device.
              </p>
              <Button variant="destructive" onClick={async () => {
                if (confirm('Are you sure you want to logout?')) {
                  await fetch('/api/auth/logout', { method: 'POST' });
                  window.location.href = '/login';
                }
              }}>
                Logout
              </Button>
            </section>
          </div>

          {/* Edit Provider Dialog */}
          <Dialog
            open={!!editingProviderId}
            onOpenChange={(open: boolean) => !open && closeDialogs()}
          >
            <DialogContent className="sm:max-w-[550px] p-0 overflow-hidden bg-background border-border shadow-2xl">
              <DialogHeader className="p-6 pb-2 bg-muted/50">
                <DialogTitle className="text-2xl font-serif text-foreground">Edit Provider</DialogTitle>
              </DialogHeader>
              <div className="p-6 pt-2">
                <ProviderForm
                  mode="edit"
                  provider={editingProvider}
                  onSave={closeDialogs}
                  onCancel={closeDialogs}
                />
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>
    </div>
  );
}
