"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
} from "@/components/ui/dialog";
import { apiRequest } from "@/lib/queryClient";
import {
  Settings as SettingsIcon,
  Building2,
  Mail,
  Users,
  Shield,
  Save,
  Key,
  Phone,
  Check,
  Plus,
  Edit,
} from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { User } from "@/models/User";
import { EmailTemplate } from "@/models/EmailTemplate";

function Settings() {
  const { user } = useAuth();
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // State for different settings sections
  const [isEmailTemplateDialogOpen, setIsEmailTemplateDialogOpen] =
    useState(false);
  const [currentTemplate, setCurrentTemplate] = useState<EmailTemplate | null>(
    null
  );
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const { data: users, isLoading } = useQuery<any>({
    queryKey: ["/users"],
  });
  // Fetch email templates
  const { data: emailTemplates = [] } = useQuery<EmailTemplate[]>({
    queryKey: ["/email-templates"],
  });

  // Password change mutation
  const changePasswordMutation = useMutation({
    mutationFn: (data: { newPassword: string }) =>
      apiRequest("PATCH", `/users/${user?.id}/password`, data),
    onSuccess: () => {
      setNewPassword("");
      setConfirmPassword("");
      toast({
        title: "Password changed",
        description: "Your password has been updated successfully.",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to change password. Please try again.",
        variant: "destructive",
      });
    },
  });

  // Email template mutation
  const saveTemplateMutation = useMutation({
    mutationFn: (data: any) => {
      if (currentTemplate?.id) {
        return apiRequest(
          "PATCH",
          `/email-templates/${currentTemplate.id}`,
          data
        );
      } else {
        return apiRequest("POST", "/email-templates", {
          ...data,
        });
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/email-templates"] });
      queryClient.refetchQueries({
        queryKey: ["/email-templates"],
      });
      setIsEmailTemplateDialogOpen(false);
      setCurrentTemplate(null);
      toast({
        title: "Template saved",
        description: "Email template has been saved successfully.",
      });
    },
  });

  const handlePasswordChange = () => {
    if (newPassword !== confirmPassword) {
      toast({
        title: "Password mismatch",
        description: "New password and confirmation do not match.",
        variant: "destructive",
      });
      return;
    }
    if (newPassword.length < 6) {
      toast({
        title: "Password too short",
        description: "Password must be at least 6 characters long.",
        variant: "destructive",
      });
      return;
    }
    changePasswordMutation.mutate({ newPassword });
  };

  const handleEmailTemplateSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const data = {
      name: formData.get("templateName") as string,
      subject: formData.get("templateSubject") as string,
      content: formData.get("templateContent") as string,
      isDefault: formData.get("isDefault") === "on",
    };
    saveTemplateMutation.mutate(data);
  };

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/4"></div>
          <div className="h-4 bg-gray-200 rounded w-1/2"></div>
          <div className="space-y-2">
            <div className="h-20 bg-gray-200 rounded"></div>
            <div className="h-20 bg-gray-200 rounded"></div>
            <div className="h-20 bg-gray-200 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 lg:p-8 space-y-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-2xl font-playfair font-bold text-primary flex items-center gap-2">
            <SettingsIcon className="h-6 w-6" />
            Museum Settings
          </h1>
          <p className="text-muted-foreground">
            Manage your museum profile, users, and preferences
          </p>
        </div>
        <Badge
          variant="outline"
          className="bg-green-50 text-green-700 border-green-200"
        >
          <Check className="h-3 w-3 mr-1" />
          Account Active
        </Badge>
      </div>

      <Tabs defaultValue="security" className="space-y-6">
        <TabsList className="grid w-full grid-cols-2 lg:grid-cols-5">
          <TabsTrigger value="security" className="flex items-center gap-2">
            <Shield className="h-4 w-4" />
            Security
          </TabsTrigger>
          <TabsTrigger value="email" className="flex items-center gap-2">
            <Mail className="h-4 w-4" />
            Email
          </TabsTrigger>
        </TabsList>
        {/* Security Settings */}
        <TabsContent value="security" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Shield className="h-5 w-5" />
                Security Settings
              </CardTitle>
              <p className="text-sm text-muted-foreground">
                Manage your account security and password
              </p>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Password Change */}
              <div className="space-y-4">
                <div className="flex items-center gap-2">
                  <Key className="h-5 w-5" />
                  <h3 className="text-lg font-medium">Change Password</h3>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="newPassword">New Password</Label>
                    <Input
                      id="newPassword"
                      type="password"
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      placeholder="Enter new password"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="confirmPassword">Confirm Password</Label>
                    <Input
                      id="confirmPassword"
                      type="password"
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      placeholder="Confirm new password"
                    />
                  </div>
                </div>
                <Button
                  onClick={handlePasswordChange}
                  disabled={
                    !newPassword ||
                    !confirmPassword ||
                    changePasswordMutation.isPending
                  }
                >
                  <Key className="h-4 w-4 mr-2" />
                  {changePasswordMutation.isPending
                    ? "Changing..."
                    : "Change Password"}
                </Button>
              </div>

              <Separator />

              {/* Account Information */}
              <div className="space-y-4">
                <h3 className="text-lg font-medium">Account Information</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Label className="text-sm font-medium text-muted-foreground">
                      Username
                    </Label>
                    <p className="text-lg">{user?.username}</p>
                  </div>
                  <div>
                    <Label className="text-sm font-medium text-muted-foreground">
                      Email
                    </Label>
                    <p className="text-lg">{user?.email}</p>
                  </div>
                  <div>
                    <Label className="text-sm font-medium text-muted-foreground">
                      User Type
                    </Label>
                    <Badge variant="outline">{user?.userType}</Badge>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
        {/* Email Templates */}
        <TabsContent value="email" className="space-y-6">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <div>
                <CardTitle className="flex items-center gap-2">
                  <Mail className="h-5 w-5" />
                  Email Templates
                </CardTitle>
                <p className="text-sm text-muted-foreground">
                  Manage email templates for visitor communications
                </p>
              </div>
              <Dialog
                open={isEmailTemplateDialogOpen}
                onOpenChange={setIsEmailTemplateDialogOpen}
              >
                <DialogTrigger asChild>
                  <Button onClick={() => setCurrentTemplate(null)}>
                    <Plus className="h-4 w-4 mr-2" />
                    New Template
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-2xl">
                  <DialogHeader>
                    <DialogTitle>
                      {currentTemplate
                        ? "Edit Email Template"
                        : "Create Email Template"}
                    </DialogTitle>
                  </DialogHeader>
                  <form
                    onSubmit={handleEmailTemplateSubmit}
                    className="space-y-4"
                  >
                    <div className="space-y-2">
                      <Label htmlFor="templateName">Template Name</Label>
                      <Input
                        id="templateName"
                        name="templateName"
                        defaultValue={currentTemplate?.name || ""}
                        placeholder="e.g., Visitor Inquiry Response"
                        required
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="templateSubject">Email Subject</Label>
                      <Input
                        id="templateSubject"
                        name="templateSubject"
                        defaultValue={currentTemplate?.subject || ""}
                        placeholder="e.g., Thank you for your inquiry"
                        required
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="templateContent">Email Content</Label>
                      <Textarea
                        id="templateContent"
                        name="templateContent"
                        defaultValue={currentTemplate?.content || ""}
                        rows={8}
                        placeholder="Enter your email template content..."
                        required
                      />
                    </div>
                    <div className="flex items-center space-x-2">
                      <Switch
                        id="isDefault"
                        name="isDefault"
                        defaultChecked={currentTemplate?.isDefault || false}
                      />
                      <Label htmlFor="isDefault">Set as default template</Label>
                    </div>
                    <DialogFooter>
                      <Button
                        type="button"
                        variant="outline"
                        onClick={() => setIsEmailTemplateDialogOpen(false)}
                      >
                        Cancel
                      </Button>
                      <Button
                        type="submit"
                        disabled={saveTemplateMutation.isPending}
                      >
                        <Save className="h-4 w-4 mr-2" />
                        {saveTemplateMutation.isPending
                          ? "Saving..."
                          : "Save Template"}
                      </Button>
                    </DialogFooter>
                  </form>
                </DialogContent>
              </Dialog>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {emailTemplates && emailTemplates.length > 0 ? (
                  emailTemplates.map((template: EmailTemplate) => (
                    <div
                      key={template.id}
                      className="flex items-center justify-between p-4 border rounded-lg"
                    >
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <p className="font-medium">{template.name}</p>
                          {template.isDefault && (
                            <Badge variant="default" className="text-xs">
                              Default
                            </Badge>
                          )}
                        </div>
                        <p className="text-sm text-muted-foreground">
                          Subject: {template.subject}
                        </p>
                        <p className="text-xs text-muted-foreground mt-1">
                          {template.content.substring(0, 100)}...
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setCurrentTemplate(template);
                            setIsEmailTemplateDialogOpen(true);
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="text-center py-8">
                    <Mail className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                    <p className="text-lg font-medium">No email templates</p>
                    <p className="text-muted-foreground">
                      Create your first email template to improve visitor
                      communications
                    </p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

export default Settings;
