"use client"

import { useState } from "react"
import { useForm } from "react-hook-form"
import { Plus, X } from "lucide-react"

import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
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 { Checkbox } from "@/components/ui/checkbox"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Separator } from "@/components/ui/separator"

interface PrimaryContact {
  firstName: string
  lastName: string
  phone: string
  email: string
  countryCode: string
  isPrimary: boolean
}

interface CPFirmFormData {
  companyName: string
  website: string
  address: string
  city: string
  state: string
  country: string
  baseCommissionRate: string
  notes: string
  primaryContacts: PrimaryContact[]
}

interface AddCPFirmSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onSubmit: (data: CPFirmFormData) => void
}

const states = [
  "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh",
  "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jharkhand", "Karnataka",
  "Kerala", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram",
  "Nagaland", "Odisha", "Punjab", "Rajasthan", "Sikkim", "Tamil Nadu",
  "Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal"
]

const countries = ["India", "United States", "United Kingdom", "Canada", "Australia"]

const cities = ["Mumbai", "Delhi", "Bangalore", "Hyderabad", "Chennai", "Kolkata", "Pune", "Ahmedabad"]

export function AddCPFirmSheet({ open, onOpenChange, onSubmit }: AddCPFirmSheetProps) {
  const { register, handleSubmit, formState: { errors }, reset, setValue, watch } = useForm<CPFirmFormData>({
    defaultValues: {
      companyName: "",
      website: "",
      address: "",
      city: "",
      state: "",
      country: "India",
      baseCommissionRate: "",
      notes: "",
      primaryContacts: []
    }
  })

  const [primaryContacts, setPrimaryContacts] = useState<PrimaryContact[]>([{
    firstName: "",
    lastName: "",
    phone: "",
    email: "",
    countryCode: "+91",
    isPrimary: true
  }])

  const addContact = () => {
    setPrimaryContacts([...primaryContacts, {
      firstName: "",
      lastName: "",
      phone: "",
      email: "",
      countryCode: "+91",
      isPrimary: false
    }])
  }

  const removeContact = (index: number) => {
    if (primaryContacts.length > 1) {
      setPrimaryContacts(primaryContacts.filter((_, i) => i !== index))
    }
  }

  const updateContact = (index: number, field: keyof PrimaryContact, value: string | boolean) => {
    const updated = [...primaryContacts]
    if (field === 'isPrimary' && value === true) {
      // If setting this contact as primary, unset all others
      updated.forEach((contact, i) => {
        contact.isPrimary = i === index
      })
    } else {
      updated[index][field] = value as any
    }
    setPrimaryContacts(updated)
  }

  const onFormSubmit = (data: CPFirmFormData) => {
    const formData = {
      ...data,
      primaryContacts
    }
    onSubmit(formData)
    reset()
    setPrimaryContacts([{
      firstName: "",
      lastName: "",
      phone: "",
      email: "",
      countryCode: "+91",
      isPrimary: true
    }])
  }

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="sm:max-w-[600px] flex flex-col p-0">
        <SheetHeader className="px-6 py-4 border-b sticky top-0 bg-background z-10">
          <SheetTitle>Add Channel Partner Company</SheetTitle>
          <SheetDescription>
            Add a new channel partner company with their company and contact details.
          </SheetDescription>
        </SheetHeader>

        <div className="flex-1 overflow-y-auto px-6 py-6">
          <form id="cp-firm-form" onSubmit={handleSubmit(onFormSubmit)} className="space-y-6">
            {/* Company Information */}
            <div className="space-y-4">
              <h3 className="text-sm font-semibold">Company Information</h3>
              
              <div className="space-y-2">
                <Label htmlFor="companyName">CP Company Name *</Label>
                <Input
                  id="companyName"
                  {...register("companyName", { required: "Company name is required" })}
                  placeholder="Enter company name"
                />
                {errors.companyName && (
                  <p className="text-sm text-destructive">{errors.companyName.message}</p>
                )}
              </div>

            <div className="space-y-2">
              <Label htmlFor="baseCommissionRate">Base Commission Rate</Label>
              <Input
                id="baseCommissionRate"
                {...register("baseCommissionRate")}
                placeholder="e.g., 2.5%"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="address">Address</Label>
              <Input
                id="address"
                {...register("address")}
                placeholder="Enter address"
              />
            </div>

              <div className="space-y-2">
                <Label htmlFor="city">City</Label>
                <Select onValueChange={(value) => setValue("city", value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select city" />
                  </SelectTrigger>
                  <SelectContent>
                    {cities.map((city) => (
                      <SelectItem key={city} value={city}>
                        {city}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="state">State</Label>
                  <Select onValueChange={(value) => setValue("state", value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select state" />
                    </SelectTrigger>
                    <SelectContent>
                      {states.map((state) => (
                        <SelectItem key={state} value={state}>
                          {state}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="country">Country</Label>
                  <Select defaultValue="India" onValueChange={(value) => setValue("country", value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select country" />
                    </SelectTrigger>
                    <SelectContent>
                      {countries.map((country) => (
                        <SelectItem key={country} value={country}>
                          {country}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            <Separator />

            {/* Primary Contact Details */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="text-sm font-semibold">Primary Contact Details</h3>
                <Button type="button" variant="outline" size="sm" onClick={addContact}>
                  <Plus className="h-4 w-4 mr-1" />
                  Add Contact
                </Button>
              </div>

              {primaryContacts.map((contact, index) => (
                <div key={index} className="space-y-4 p-4 border rounded-lg relative">
                  {primaryContacts.length > 1 && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="absolute top-2 right-2 h-6 w-6"
                      onClick={() => removeContact(index)}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  )}

                  <div className="flex items-center space-x-2 mb-2">
                    <Checkbox
                      id={`primary-${index}`}
                      checked={contact.isPrimary}
                      onCheckedChange={(checked) => updateContact(index, "isPrimary", checked as boolean)}
                    />
                    <Label
                      htmlFor={`primary-${index}`}
                      className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Set as Primary Contact
                    </Label>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>First Name</Label>
                      <Input
                        value={contact.firstName}
                        onChange={(e) => updateContact(index, "firstName", e.target.value)}
                        placeholder="First name"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Last Name</Label>
                      <Input
                        value={contact.lastName}
                        onChange={(e) => updateContact(index, "lastName", e.target.value)}
                        placeholder="Last name"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label>Phone Number</Label>
                    <div className="flex gap-2">
                      <Select
                        value={contact.countryCode}
                        onValueChange={(value) => updateContact(index, "countryCode", value)}
                      >
                        <SelectTrigger className="w-[100px]">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="+91">+91</SelectItem>
                          <SelectItem value="+1">+1</SelectItem>
                          <SelectItem value="+44">+44</SelectItem>
                          <SelectItem value="+61">+61</SelectItem>
                        </SelectContent>
                      </Select>
                      <Input
                        value={contact.phone}
                        onChange={(e) => updateContact(index, "phone", e.target.value)}
                        placeholder="Phone number"
                        className="flex-1"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label>Email</Label>
                    <Input
                      type="email"
                      value={contact.email}
                      onChange={(e) => updateContact(index, "email", e.target.value)}
                      placeholder="email@example.com"
                    />
                  </div>
                </div>
              ))}
            </div>
          </form>
        </div>

        <div className="px-6 py-4 border-t sticky bottom-0 bg-background flex justify-end gap-2">
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button type="submit" form="cp-firm-form">
            Add CP Company
          </Button>
        </div>
      </SheetContent>
    </Sheet>
  )
}
