import React, { useState, useEffect } from "react";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient, useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Building2, ArrowLeft, Save, Loader2 } from "lucide-react";
import PageHeader from "@/components/common/PageHeader";
import { useToast } from "@/components/ui/use-toast";

export default function EditVendor() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const urlParams = new URLSearchParams(window.location.search);
  const vendorId = urlParams.get('id');

  const { data: allVendors = [], isLoading } = useQuery({
    queryKey: ['vendors'],
    queryFn: () => base44.entities.Vendor.list(),
    initialData: [],
  });

  const vendor = allVendors.find(v => v.id === vendorId);

  const [vendorData, setVendorData] = useState({
    vendor_number: "",
    legal_name: "",
    doing_business_as: "",
    tax_id: "",
    business_type: "LLC",
    primary_contact_name: "",
    primary_contact_email: "",
    primary_contact_phone: "",
    billing_address: "",
    service_address: "",
    coverage_regions: [],
    eligible_roles: [],
    insurance_expiry: "",
    approval_status: "approved",
    is_active: true,
    notes: ""
  });

  const [regionInput, setRegionInput] = useState("");
  const [roleInput, setRoleInput] = useState("");

  useEffect(() => {
    if (vendor) {
      setVendorData({
        vendor_number: vendor.vendor_number || "",
        legal_name: vendor.legal_name || "",
        doing_business_as: vendor.doing_business_as || "",
        tax_id: vendor.tax_id || "",
        business_type: vendor.business_type || "LLC",
        primary_contact_name: vendor.primary_contact_name || "",
        primary_contact_email: vendor.primary_contact_email || "",
        primary_contact_phone: vendor.primary_contact_phone || "",
        billing_address: vendor.billing_address || "",
        service_address: vendor.service_address || "",
        coverage_regions: vendor.coverage_regions || [],
        eligible_roles: vendor.eligible_roles || [],
        insurance_expiry: vendor.insurance_expiry || "",
        approval_status: vendor.approval_status || "approved",
        is_active: vendor.is_active !== undefined ? vendor.is_active : true,
        notes: vendor.notes || ""
      });
    }
  }, [vendor]);

  const updateVendorMutation = useMutation({
    mutationFn: ({ id, data }) => base44.entities.Vendor.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vendors'] });
      toast({
        title: "Vendor Updated",
        description: "Vendor information has been successfully updated",
      });
      navigate(createPageUrl("VendorManagement"));
    },
  });

  const handleAddRegion = () => {
    if (regionInput.trim() && !vendorData.coverage_regions.includes(regionInput.trim())) {
      setVendorData({
        ...vendorData,
        coverage_regions: [...vendorData.coverage_regions, regionInput.trim()]
      });
      setRegionInput("");
    }
  };

  const handleRemoveRegion = (index) => {
    setVendorData({
      ...vendorData,
      coverage_regions: vendorData.coverage_regions.filter((_, i) => i !== index)
    });
  };

  const handleAddRole = () => {
    if (roleInput.trim() && !vendorData.eligible_roles.includes(roleInput.trim())) {
      setVendorData({
        ...vendorData,
        eligible_roles: [...vendorData.eligible_roles, roleInput.trim()]
      });
      setRoleInput("");
    }
  };

  const handleRemoveRole = (index) => {
    setVendorData({
      ...vendorData,
      eligible_roles: vendorData.eligible_roles.filter((_, i) => i !== index)
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    updateVendorMutation.mutate({ id: vendorId, data: vendorData });
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin text-[#0A39DF]" />
      </div>
    );
  }

  if (!vendor) {
    return (
      <div className="p-8 text-center">
        <h2 className="text-2xl font-bold text-slate-900 mb-4">Vendor Not Found</h2>
        <Button onClick={() => navigate(createPageUrl("VendorManagement"))}>
          Back to Vendors
        </Button>
      </div>
    );
  }

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-4xl mx-auto">
        <PageHeader
          title="Edit Vendor"
          subtitle={`Update information for ${vendor.legal_name || vendor.doing_business_as}`}
          backTo={createPageUrl("VendorManagement")}
          backButtonLabel="Back to Vendors"
        />

        <form onSubmit={handleSubmit}>
          {/* Basic Information */}
          <Card className="mb-6 border-slate-200 shadow-lg">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
              <CardTitle className="flex items-center gap-2">
                <Building2 className="w-5 h-5 text-[#0A39DF]" />
                Basic Information
              </CardTitle>
            </CardHeader>
            <CardContent className="p-6 space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <Label htmlFor="vendor_number">Vendor Number</Label>
                  <Input
                    id="vendor_number"
                    value={vendorData.vendor_number}
                    disabled
                    className="bg-slate-100"
                  />
                </div>

                <div>
                  <Label htmlFor="approval_status">Status</Label>
                  <Select
                    value={vendorData.approval_status}
                    onValueChange={(value) => setVendorData({...vendorData, approval_status: value})}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="pending">Pending</SelectItem>
                      <SelectItem value="approved">Approved</SelectItem>
                      <SelectItem value="suspended">Suspended</SelectItem>
                      <SelectItem value="terminated">Terminated</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="md:col-span-2">
                  <Label htmlFor="legal_name">Legal Business Name *</Label>
                  <Input
                    id="legal_name"
                    placeholder="e.g., ABC Staffing LLC"
                    value={vendorData.legal_name}
                    onChange={(e) => setVendorData({...vendorData, legal_name: e.target.value})}
                    required
                  />
                </div>

                <div className="md:col-span-2">
                  <Label htmlFor="doing_business_as">Doing Business As (DBA)</Label>
                  <Input
                    id="doing_business_as"
                    placeholder="e.g., ABC Staff"
                    value={vendorData.doing_business_as}
                    onChange={(e) => setVendorData({...vendorData, doing_business_as: e.target.value})}
                  />
                </div>

                <div>
                  <Label htmlFor="tax_id">Federal Tax ID / EIN</Label>
                  <Input
                    id="tax_id"
                    placeholder="12-3456789"
                    value={vendorData.tax_id}
                    onChange={(e) => setVendorData({...vendorData, tax_id: e.target.value})}
                  />
                </div>

                <div>
                  <Label htmlFor="business_type">Business Type</Label>
                  <Select
                    value={vendorData.business_type}
                    onValueChange={(value) => setVendorData({...vendorData, business_type: value})}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Corporation">Corporation</SelectItem>
                      <SelectItem value="LLC">LLC</SelectItem>
                      <SelectItem value="Partnership">Partnership</SelectItem>
                      <SelectItem value="Sole Proprietorship">Sole Proprietorship</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Contact Information */}
          <Card className="mb-6 border-slate-200 shadow-lg">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
              <CardTitle>Primary Contact</CardTitle>
            </CardHeader>
            <CardContent className="p-6 space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="md:col-span-2">
                  <Label htmlFor="primary_contact_name">Contact Name</Label>
                  <Input
                    id="primary_contact_name"
                    placeholder="John Doe"
                    value={vendorData.primary_contact_name}
                    onChange={(e) => setVendorData({...vendorData, primary_contact_name: e.target.value})}
                  />
                </div>

                <div>
                  <Label htmlFor="primary_contact_email">Email *</Label>
                  <Input
                    id="primary_contact_email"
                    type="email"
                    placeholder="john@vendor.com"
                    value={vendorData.primary_contact_email}
                    onChange={(e) => setVendorData({...vendorData, primary_contact_email: e.target.value})}
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="primary_contact_phone">Phone</Label>
                  <Input
                    id="primary_contact_phone"
                    type="tel"
                    placeholder="(555) 123-4567"
                    value={vendorData.primary_contact_phone}
                    onChange={(e) => setVendorData({...vendorData, primary_contact_phone: e.target.value})}
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Coverage & Services */}
          <Card className="mb-6 border-slate-200 shadow-lg">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
              <CardTitle>Coverage & Services</CardTitle>
            </CardHeader>
            <CardContent className="p-6 space-y-6">
              <div>
                <Label>Coverage Regions</Label>
                <div className="flex gap-2 mb-2">
                  <Input
                    placeholder="Add region (e.g., San Francisco Bay Area)"
                    value={regionInput}
                    onChange={(e) => setRegionInput(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddRegion())}
                  />
                  <Button type="button" onClick={handleAddRegion} variant="outline">
                    Add
                  </Button>
                </div>
                <div className="flex flex-wrap gap-2">
                  {vendorData.coverage_regions.map((region, i) => (
                    <span key={i} className="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm flex items-center gap-2">
                      {region}
                      <button type="button" onClick={() => handleRemoveRegion(i)} className="text-blue-900 hover:text-blue-700">×</button>
                    </span>
                  ))}
                </div>
              </div>

              <div>
                <Label>Eligible Roles</Label>
                <div className="flex gap-2 mb-2">
                  <Input
                    placeholder="Add role (e.g., Server, Bartender)"
                    value={roleInput}
                    onChange={(e) => setRoleInput(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddRole())}
                  />
                  <Button type="button" onClick={handleAddRole} variant="outline">
                    Add
                  </Button>
                </div>
                <div className="flex flex-wrap gap-2">
                  {vendorData.eligible_roles.map((role, i) => (
                    <span key={i} className="bg-purple-100 text-purple-700 px-3 py-1 rounded-full text-sm flex items-center gap-2">
                      {role}
                      <button type="button" onClick={() => handleRemoveRole(i)} className="text-purple-900 hover:text-purple-700">×</button>
                    </span>
                  ))}
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="md:col-span-2">
                  <Label htmlFor="billing_address">Billing Address</Label>
                  <Textarea
                    id="billing_address"
                    rows={3}
                    placeholder="123 Main St, San Francisco, CA 94102"
                    value={vendorData.billing_address}
                    onChange={(e) => setVendorData({...vendorData, billing_address: e.target.value})}
                  />
                </div>

                <div className="md:col-span-2">
                  <Label htmlFor="service_address">Service Address</Label>
                  <Textarea
                    id="service_address"
                    rows={3}
                    placeholder="456 Service St, San Francisco, CA 94103"
                    value={vendorData.service_address}
                    onChange={(e) => setVendorData({...vendorData, service_address: e.target.value})}
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Notes */}
          <Card className="mb-6 border-slate-200 shadow-lg">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
              <CardTitle>Additional Information</CardTitle>
            </CardHeader>
            <CardContent className="p-6">
              <div>
                <Label htmlFor="notes">Internal Notes</Label>
                <Textarea
                  id="notes"
                  rows={4}
                  placeholder="Add any internal notes about this vendor..."
                  value={vendorData.notes}
                  onChange={(e) => setVendorData({...vendorData, notes: e.target.value})}
                />
              </div>
            </CardContent>
          </Card>

          {/* Action Buttons */}
          <div className="flex justify-end gap-3">
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate(createPageUrl("VendorManagement"))}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={updateVendorMutation.isPending}
              className="bg-[#0A39DF] hover:bg-[#0A39DF]/90"
            >
              {updateVendorMutation.isPending ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Updating...
                </>
              ) : (
                <>
                  <Save className="w-4 h-4 mr-2" />
                  Update Vendor
                </>
              )}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}