import { useState, useEffect } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import type { Client } from "@shared/schema";

interface SimEditModalProps {
  sim: Client | null;
  isOpen: boolean;
  onClose: () => void;
  simType: "primary" | "secondary";
}

export default function SimEditModal({ sim, isOpen, onClose, simType }: SimEditModalProps) {
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Track client view when modal opens
  useEffect(() => {
    if (isOpen && sim?.id) {
      fetch(`/api/track-view/${sim.id}`, {
        method: 'POST',
        credentials: 'include',
      }).catch(console.error);
    }
  }, [isOpen, sim?.id]);
  
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    serviceDetails: "",
    accountNumber: "",
    status: "",
    status2: "",
    category: "",
    msisdn: "",
    simSerialNumber: "",
    fup: "",
    isReseller: false,
  });

  useEffect(() => {
    if (sim) {
      setFormData({
        name: sim.name || "",
        email: sim.email || "",
        serviceDetails: sim.serviceDetails || "",
        accountNumber: sim.accountNumber || "",
        status: sim.status || "",
        status2: sim.status2 || "",
        category: sim.category || "",
        msisdn: sim.msisdn || "",
        simSerialNumber: sim.simSerialNumber || (sim as any).simNumber || "",
        fup: sim.fup || "",
        isReseller: sim.isReseller || false,
      });
    }
  }, [sim]);

  const updateSimMutation = useMutation({
    mutationFn: async (data: typeof formData) => {
      const response = await fetch(`/api/clients/${sim?.id}`, {
        method: "PUT",
        body: JSON.stringify(data),
        headers: {
          "Content-Type": "application/json",
        },
      });
      if (!response.ok) throw new Error('Failed to update SIM');
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "Success",
        description: `${sim?.category} SIM updated successfully`,
      });
      // Invalidate cache for all relevant endpoints
      queryClient.invalidateQueries({ queryKey: ["/api/clients"] });
      queryClient.invalidateQueries({ queryKey: ["/api/clients/telkom"] });
      onClose();
    },
    onError: (error) => {
      toast({
        title: "Error",
        description: "Failed to update SIM",
        variant: "destructive",
      });
      console.error("Update error:", error);
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    updateSimMutation.mutate(formData);
  };

  const handleInputChange = (field: string, value: string | boolean) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  if (!sim) return null;

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto" aria-describedby="edit-sim-description">
        <DialogHeader>
          <DialogTitle>
            Edit {sim.category} SIM
          </DialogTitle>
          <div className="space-y-2">
            <p id="edit-sim-description" className="text-sm text-gray-600">
              SIM Serial: {sim.simSerialNumber || (sim as any).simNumber || "N/A"} | MSISDN: {sim.msisdn || "N/A"}
            </p>
            {!sim.isPrimarySim && (sim as any).primarySimInfo && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                <p className="text-sm font-medium text-blue-900 mb-1">Secondary SIM Relationship</p>
                <p className="text-sm text-blue-700">
                  Linked to Primary SIM: <span className="font-medium">{(sim as any).primarySimInfo.name}</span>
                </p>
                <p className="text-sm text-blue-600">
                  Primary Account: {(sim as any).primarySimInfo.accountNumber || "N/A"}
                </p>
              </div>
            )}
          </div>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="name">Name</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => handleInputChange("name", e.target.value)}
                placeholder="Enter client name"
              />
            </div>

            <div>
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                type="email"
                value={formData.email}
                onChange={(e) => handleInputChange("email", e.target.value)}
                placeholder="Enter email address"
              />
            </div>

            <div>
              <Label htmlFor="accountNumber">Account Number</Label>
              <Input
                id="accountNumber"
                value={formData.accountNumber}
                onChange={(e) => handleInputChange("accountNumber", e.target.value)}
                placeholder="Enter account number"
              />
            </div>

            <div>
              <Label htmlFor="category">Category</Label>
              <Input
                id="category"
                value={formData.category}
                disabled
                className="bg-gray-50 cursor-not-allowed"
              />
            </div>

            <div>
              <Label htmlFor="status">Status</Label>
              <Select value={formData.status} onValueChange={(value) => handleInputChange("status", value)}>
                <SelectTrigger>
                  <SelectValue placeholder="Select status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Active">Active</SelectItem>
                  <SelectItem value="Suspended">Suspended</SelectItem>
                  <SelectItem value="Cancelled">Cancelled</SelectItem>
                  <SelectItem value="Debit Order Unpaid">Debit Order Unpaid</SelectItem>
                  <SelectItem value="Pending">Pending</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="status2">Status 2</Label>
              <Input
                id="status2"
                value={formData.status2}
                onChange={(e) => handleInputChange("status2", e.target.value.slice(0, 40))}
                placeholder="Enter secondary status"
                maxLength={40}
              />
            </div>

            <div>
              <Label htmlFor="msisdn">MSISDN</Label>
              <Input
                id="msisdn"
                value={formData.msisdn}
                onChange={(e) => handleInputChange("msisdn", e.target.value)}
                placeholder="Enter MSISDN"
              />
            </div>

            <div>
              <Label htmlFor="simSerialNumber">SIM Serial Number</Label>
              <Input
                id="simSerialNumber"
                value={formData.simSerialNumber}
                onChange={(e) => handleInputChange("simSerialNumber", e.target.value)}
                placeholder="Enter SIM serial number"
              />
            </div>
            
            {/* FUP field - only show for Telkom clients */}
            {formData.category === "Telkom" && (
              <div>
                <Label htmlFor="fup">FUP (GB)</Label>
                <Input
                  id="fup"
                  type="number"
                  value={formData.fup}
                  onChange={(e) => handleInputChange("fup", e.target.value)}
                  placeholder="Enter FUP in GB (e.g., 50)"
                />
                <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"
              value={formData.serviceDetails}
              onChange={(e) => handleInputChange("serviceDetails", e.target.value)}
              placeholder="Enter service details"
              rows={3}
            />
          </div>

          <div className="flex items-center space-x-2 p-4 bg-blue-50 border border-blue-200 rounded-lg">
            <Checkbox
              id="isReseller"
              checked={formData.isReseller}
              onCheckedChange={(checked) => handleInputChange("isReseller", checked as boolean)}
            />
            <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>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>
              Cancel
            </Button>
            <Button type="submit" disabled={updateSimMutation.isPending}>
              {updateSimMutation.isPending ? "Updating..." : "Update SIM"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}