import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { insertClientSchema, type Client, type InsertClient, type Category } from "@shared/schema";
import { X } from "lucide-react";

interface ClientEditModalProps {
  client: Client | null;
  isOpen: boolean;
  onClose: () => void;
  defaultCategory?: string;
}

export default function ClientEditModal({ client, isOpen, onClose, defaultCategory }: ClientEditModalProps) {
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Track client view when modal opens for existing client
  useEffect(() => {
    if (isOpen && client?.id) {
      fetch(`/api/track-view/${client.id}`, {
        method: 'POST',
        credentials: 'include',
      }).catch(console.error);
    }
  }, [isOpen, client?.id]);
  
  // Fetch categories from the database
  const { data: categories = [] } = useQuery<Category[]>({
    queryKey: ["/api/categories"],
    enabled: isOpen,
  });
  
  const form = useForm<InsertClient>({
    resolver: zodResolver(insertClientSchema),
    defaultValues: {
      name: client?.name || "",
      email: client?.email || "",
      category: client?.category || defaultCategory || "",
      status: client?.status || "Active",
      status2: client?.status2 || "",
      msisdn: client?.msisdn || "",
      simSerialNumber: client?.simSerialNumber || "",
      serviceDetails: client?.serviceDetails || "",
      accountNumber: client?.accountNumber || "",
      contactInfo: client?.contactInfo || "",
      address: client?.address || "",
      notes: client?.notes || "",
      fup: client?.fup || "",
      isReseller: client?.isReseller || false,
    },
  });

  const updateMutation = useMutation({
    mutationFn: async (data: InsertClient) => {
      if (client) {
        return apiRequest("PUT", `/api/clients/${client.id}`, data);
      } else {
        return apiRequest("POST", "/api/clients", data);
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/clients"] });
      queryClient.invalidateQueries({ queryKey: ["/api/clients/telkom"] });
      queryClient.invalidateQueries({ queryKey: ["/api/stats"] });
      toast({
        title: "Success",
        description: `Client ${client ? "updated" : "created"} successfully`,
      });
      onClose();
      form.reset();
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || `Failed to ${client ? "update" : "create"} client`,
        variant: "destructive",
      });
    },
  });

  const onSubmit = (data: InsertClient) => {
    updateMutation.mutate(data);
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader className="flex-shrink-0">
          <DialogTitle className="flex items-center justify-between">
            {client ? "Edit Client Information" : "Add New Client"}
            <Button variant="ghost" size="sm" onClick={onClose}>
              <X size={20} />
            </Button>
          </DialogTitle>
          <DialogDescription>
            {client ? "Update the client's information and service details." : "Enter the details for the new client account."}
          </DialogDescription>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto pr-2">
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <Label htmlFor="name">Client Name</Label>
                <Input
                  id="name"
                  {...form.register("name")}
                  className="mt-2"
                />
                {form.formState.errors.name && (
                  <p className="text-sm text-error mt-1">{form.formState.errors.name.message}</p>
                )}
              </div>
              <div>
                <Label htmlFor="email">Email</Label>
                <Input
                  id="email"
                  type="email"
                  {...form.register("email")}
                  className="mt-2"
                />
                {form.formState.errors.email && (
                  <p className="text-sm text-error mt-1">{form.formState.errors.email.message}</p>
                )}
              </div>
              <div>
                <Label htmlFor="contactInfo">Contact Info</Label>
                <Input
                  id="contactInfo"
                  {...form.register("contactInfo")}
                  className="mt-2"
                />
                {form.formState.errors.contactInfo && (
                  <p className="text-sm text-error mt-1">{form.formState.errors.contactInfo.message}</p>
                )}
              </div>
              <div>
                <Label htmlFor="accountNumber">
                  {(form.watch("category") === "Axxess (Fibre Lines)" || form.watch("category") === "OpenServe (Fibre Lines)") ? "Username/B Number" : "Account Number"}
                </Label>
                <Input
                  id="accountNumber"
                  {...form.register("accountNumber")}
                  className="mt-2"
                  placeholder={
                    (form.watch("category") === "Axxess (Fibre Lines)" || form.watch("category") === "OpenServe (Fibre Lines)")
                      ? "Enter username or B number" 
                      : "Enter account number"
                  }
                />
                {form.formState.errors.accountNumber && (
                  <p className="text-sm text-error mt-1">{form.formState.errors.accountNumber.message}</p>
                )}
              </div>
              <div>
                <Label htmlFor="category">Category</Label>
                <Select
                  value={form.watch("category")}
                  onValueChange={(value) => form.setValue("category", value)}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select category" />
                  </SelectTrigger>
                  <SelectContent>
                    {categories.map((category) => (
                      <SelectItem key={category.id} value={category.name}>
                        {category.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="status">Status</Label>
                <Select
                  value={form.watch("status") || "Active"}
                  onValueChange={(value) => form.setValue("status", value)}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Active">Active</SelectItem>
                    <SelectItem value="Suspended">Suspended</SelectItem>
                    <SelectItem value="Cancelled">Cancelled</SelectItem>
                    <SelectItem value="Pending">Pending</SelectItem>
                    <SelectItem value="Debit Order Unpaid">Debit Order Unpaid</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="status2">Status 2</Label>
                <Input
                  id="status2"
                  {...form.register("status2")}
                  className="mt-2"
                  placeholder="Enter secondary status"
                />
              </div>
              <div>
                <Label htmlFor="msisdn">
                  {(form.watch("category") === "Axxess (Fibre Lines)" || form.watch("category") === "OpenServe (Fibre Lines)") ? "Fibre Speed" : "MSISDN"}
                </Label>
                <Input
                  id="msisdn"
                  {...form.register("msisdn")}
                  className="mt-2"
                  placeholder={
                    (form.watch("category") === "Axxess (Fibre Lines)" || form.watch("category") === "OpenServe (Fibre Lines)")
                      ? "Enter fibre speed (e.g., 100Mbps)" 
                      : "Enter MSISDN"
                  }
                />
              </div>
              <div>
                <Label htmlFor="simSerialNumber">SIM Serial Number</Label>
                <Input
                  id="simSerialNumber"
                  {...form.register("simSerialNumber")}
                  className="mt-2"
                  placeholder="Enter SIM serial number"
                />
              </div>
              
              {/* FUP field - only show for Telkom clients */}
              {form.watch("category") === "Telkom" && (
                <div>
                  <Label htmlFor="fup">FUP (GB)</Label>
                  <Input
                    id="fup"
                    {...form.register("fup")}
                    className="mt-2"
                    placeholder="Enter FUP in GB (e.g., 50)"
                    type="number"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    Fair Usage Policy limit in gigabytes (optional)
                  </p>
                </div>
              )}
            </div>

            <div>
              <Label htmlFor="serviceDetails">Service Details</Label>
              <Textarea
                id="serviceDetails"
                {...form.register("serviceDetails")}
                rows={3}
                className="mt-2"
                placeholder="Enter service details"
              />
            </div>

            <div>
              <Label htmlFor="address">Address</Label>
              <Textarea
                id="address"
                {...form.register("address")}
                rows={3}
                className="mt-2"
              />
            </div>

            <div>
              <Label htmlFor="notes">Notes</Label>
              <Textarea
                id="notes"
                {...form.register("notes")}
                rows={2}
                className="mt-2"
                placeholder="Additional notes or comments..."
              />
            </div>

            <div className="flex items-center space-x-2 p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <Checkbox
                id="isReseller"
                checked={form.watch("isReseller") === true}
                onCheckedChange={(checked) => form.setValue("isReseller", !!checked)}
              />
              <Label htmlFor="isReseller" className="text-sm font-medium text-blue-900">
                Mark as Reseller Client
              </Label>
              <span className="text-xs text-blue-700">
                (Reseller clients will be displayed with special blue styling)
              </span>
            </div>

            <div className="flex items-center justify-end space-x-4 pt-6 border-t border-gray-200">
              <Button type="button" variant="outline" onClick={onClose}>
                Cancel
              </Button>
              <Button type="submit" disabled={updateMutation.isPending}>
                {updateMutation.isPending ? "Saving..." : client ? "Update Client" : "Create Client"}
              </Button>
            </div>
          </form>
        </div>
      </DialogContent>
    </Dialog>
  );
}
