import React, { useState } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { Button } from "@/common/components/ui/button";
import { Input } from "@/common/components/ui/input";
import { Label } from "@/common/components/ui/label";
import { Textarea } from "@/common/components/ui/textarea";
import { Card, CardContent } from "@/common/components/ui/card";
import { 
  Plus, 
  Trash2, 
  Info, 
  ChevronRight, 
  ChevronLeft,
  Save,
  X,
  PlusCircle
} from "lucide-react";
import { format } from "date-fns";

interface Role {
  name: string;
  count: number;
  rate?: number;
}

interface Shift {
  id?: string;
  title: string;
  startTime: string;
  endTime: string;
  roles: Role[];
}

interface EventFormData {
  event_name: string;
  date: string;
  startDate: string;
  endDate: string;
  notes: string;
  po_reference: string;
  total: number;
  shifts: Shift[];
}

interface EventFormWizardProps {
  event: any;
  onSubmit: (data: any) => void;
  isSubmitting: boolean;
  currentUser: any;
  onCancel: () => void;
}

export default function EventFormWizard({ 
  event, 
  onSubmit, 
  isSubmitting, 
  onCancel 
}: EventFormWizardProps) {
  const [step, setStep] = useState(1);
  
  const { register, control, handleSubmit, formState: { errors } } = useForm<EventFormData>({
    defaultValues: {
      event_name: event?.eventName || "",
      date: event?.date ? format(new Date(event.date), "yyyy-MM-dd") : "",
      startDate: event?.startDate ? format(new Date(event.startDate), "yyyy-MM-dd'T'HH:mm") : "",
      endDate: event?.endDate ? format(new Date(event.endDate), "yyyy-MM-dd'T'HH:mm") : "",
      notes: event?.notes || "",
      po_reference: event?.poReference || "",
      total: event?.total || 0,
      shifts: event?.shifts?.map((s: any) => ({
        ...s,
        roles: Array.isArray(s.roles) ? s.roles : []
      })) || []
    }
  });

  const { fields: shiftFields, append: appendShift, remove: removeShift } = useFieldArray({
    control,
    name: "shifts"
  });

  const nextStep = () => setStep(prev => prev + 1);
  const prevStep = () => setStep(prev => prev - 1);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between mb-8">
        <div className="flex items-center gap-4">
          {[1, 2].map((i) => (
            <React.Fragment key={i}>
              <div 
                className={`w-10 h-10 rounded-full flex items-center justify-center font-bold transition-colors ${
                  step >= i ? "bg-primary text-white" : "bg-muted text-muted-foreground"
                }`}
              >
                {i}
              </div>
              {i < 2 && <div className={`w-12 h-0.5 ${step > i ? "bg-primary" : "bg-muted"}`} />}
            </React.Fragment>
          ))}
        </div>
        <div className="text-right">
          <p className="text-xs font-black text-muted-foreground uppercase tracking-widest">
            Step {step} of 2
          </p>
          <p className="text-sm font-bold text-primary-text">
            {step === 1 ? "Order Details" : "Shift Management"}
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)}>
        {step === 1 && (
          <div className="space-y-6 animate-in fade-in slide-in-from-right-4 duration-300">
            <Card className="border-border shadow-sm">
              <CardContent className="p-8 space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <Label className="text-xs font-black uppercase tracking-widest text-muted-foreground">Event Name</Label>
                    <Input 
                      {...register("event_name", { required: "Event name is required" })}
                      placeholder="e.g., Annual Gala 2024"
                      className="rounded-xl h-12"
                    />
                    {errors.event_name && <p className="text-xs text-destructive font-bold">{errors.event_name.message}</p>}
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-black uppercase tracking-widest text-muted-foreground">PO Reference (Optional)</Label>
                    <Input 
                      {...register("po_reference")}
                      placeholder="PO-12345"
                      className="rounded-xl h-12"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div className="space-y-2">
                    <Label className="text-xs font-black uppercase tracking-widest text-muted-foreground">Primary Date</Label>
                    <Input 
                      type="date"
                      {...register("date", { required: "Date is required" })}
                      className="rounded-xl h-12"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-black uppercase tracking-widest text-muted-foreground">Start Date & Time</Label>
                    <Input 
                      type="datetime-local"
                      {...register("startDate", { required: "Start time is required" })}
                      className="rounded-xl h-12"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-black uppercase tracking-widest text-muted-foreground">End Date & Time</Label>
                    <Input 
                      type="datetime-local"
                      {...register("endDate", { required: "End time is required" })}
                      className="rounded-xl h-12"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label className="text-xs font-black uppercase tracking-widest text-muted-foreground">Additional Notes</Label>
                  <Textarea 
                    {...register("notes")}
                    placeholder="Enter any special instructions or requirements..."
                    className="rounded-xl min-h-[120px]"
                  />
                </div>
              </CardContent>
            </Card>

            <div className="flex justify-between pt-4">
              <Button type="button" variant="outline" onClick={onCancel} className="rounded-xl px-8 font-bold">
                Cancel
              </Button>
              <Button type="button" onClick={nextStep} className="rounded-xl px-8 font-bold" trailingIcon={<ChevronRight className="w-4 h-4" />}>
                Next: Manage Shifts
              </Button>
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="space-y-6 animate-in fade-in slide-in-from-right-4 duration-300">
            <div className="flex items-center justify-between">
              <h3 className="text-xl font-bold text-primary-text">Shifts & Staffing</h3>
              <Button 
                type="button" 
                onClick={() => appendShift({ title: "New Shift", startTime: "", endTime: "", roles: [] })}
                variant="outline"
                className="rounded-xl font-bold"
                leadingIcon={<PlusCircle className="w-4 h-4" />}
              >
                Add Shift
              </Button>
            </div>

            {shiftFields.map((field, shiftIndex) => (
              <Card key={field.id} className="border-border shadow-sm overflow-hidden">
                <div className="bg-muted/30 px-6 py-4 border-b border-border flex items-center justify-between">
                  <div className="flex items-center gap-4 flex-1">
                    <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary font-bold">
                      {shiftIndex + 1}
                    </div>
                    <Input 
                      {...register(`shifts.${shiftIndex}.title`)}
                      className="bg-transparent border-none font-bold text-lg p-0 focus-visible:ring-0"
                    />
                  </div>
                  <Button 
                    type="button" 
                    variant="ghost" 
                    size="icon" 
                    onClick={() => removeShift(shiftIndex)}
                    className="text-destructive hover:bg-destructive/10"
                  >
                    <Trash2 className="w-4 h-4" />
                  </Button>
                </div>
                <CardContent className="p-6 space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <Label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Shift Start</Label>
                      <Input 
                        type="datetime-local"
                        {...register(`shifts.${shiftIndex}.startTime`)}
                        className="rounded-xl"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Shift End</Label>
                      <Input 
                        type="datetime-local"
                        {...register(`shifts.${shiftIndex}.endTime`)}
                        className="rounded-xl"
                      />
                    </div>
                  </div>

                  <div className="space-y-4">
                    <Label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Roles & Headcount</Label>
                    <ShiftRoles 
                      shiftIndex={shiftIndex} 
                      control={control} 
                      register={register} 
                    />
                  </div>
                </CardContent>
              </Card>
            ))}

            {shiftFields.length === 0 && (
              <div className="text-center py-12 bg-muted/20 rounded-2xl border-2 border-dashed border-border">
                <Info className="w-12 h-12 text-muted-foreground/30 mx-auto mb-4" />
                <p className="font-bold text-muted-foreground">No shifts added yet.</p>
                <p className="text-sm text-muted-foreground mb-6">Every order needs at least one shift to request staff.</p>
                <Button 
                  type="button" 
                  onClick={() => appendShift({ title: "Primary Shift", startTime: "", endTime: "", roles: [] })}
                  className="rounded-xl font-bold"
                >
                  Add Your First Shift
                </Button>
              </div>
            )}

            <div className="flex justify-between pt-4">
              <Button type="button" variant="outline" onClick={prevStep} className="rounded-xl px-8 font-bold" leadingIcon={<ChevronLeft className="w-4 h-4" />}>
                Back
              </Button>
              <Button 
                type="submit" 
                disabled={isSubmitting} 
                className="rounded-xl px-12 font-bold shadow-lg shadow-primary/20"
                leadingIcon={isSubmitting ? <Plus className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
              >
                {isSubmitting ? "Saving Changes..." : "Save Order Changes"}
              </Button>
            </div>
          </div>
        )}
      </form>
    </div>
  );
}

function ShiftRoles({ shiftIndex, control, register }: { shiftIndex: number, control: any, register: any }) {
  const { fields, append, remove } = useFieldArray({
    control,
    name: `shifts.${shiftIndex}.roles`
  });

  return (
    <div className="space-y-3">
      {fields.map((role, roleIndex) => (
        <div key={role.id} className="flex items-center gap-3 bg-muted/20 p-3 rounded-xl border border-border/40">
          <div className="flex-1">
            <Input 
              {...register(`shifts.${shiftIndex}.roles.${roleIndex}.name`)}
              placeholder="Role (e.g. Bartender)"
              className="bg-transparent border-none font-bold h-8 focus-visible:ring-0"
            />
          </div>
          <div className="flex items-center gap-2">
            <Label className="text-[10px] font-black text-muted-foreground uppercase">Count</Label>
            <Input 
              type="number"
              {...register(`shifts.${shiftIndex}.roles.${roleIndex}.count`)}
              className="w-20 h-8 rounded-lg font-bold"
              min="1"
            />
          </div>
          <Button 
            type="button" 
            variant="ghost" 
            size="icon" 
            onClick={() => remove(roleIndex)}
            className="h-8 w-8 text-muted-foreground hover:text-destructive"
          >
            <X className="w-3 h-3" />
          </Button>
        </div>
      ))}
      <Button 
        type="button" 
        variant="ghost" 
        size="sm" 
        onClick={() => append({ name: "", count: 1 })}
        className="text-xs font-bold text-primary hover:bg-primary/5"
        leadingIcon={<Plus className="w-3 h-3" />}
      >
        Add Role
      </Button>
    </div>
  );
}
