import React from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { Plus, Trash2, Users, MapPin } from "lucide-react";
import ShiftRoleCard from "./ShiftRoleCard";

export default function ShiftSection({ shifts = [], onChange, addons = {}, onAddonsChange, selectedVendor }) {
  const handleAddShift = () => {
    const currentShifts = Array.isArray(shifts) ? shifts : [];
    onChange([...currentShifts, {
      shift_name: `Shift ${currentShifts.length + 1}`,
      shift_contact: "",
      location_address: "",
      roles: [{
        role: "",
        department: "",
        count: 1,
        start_time: "12:00 PM",
        end_time: "05:00 PM",
        hours: 5,
        uniform: "Type 1",
        break_minutes: 30,
        cost_per_hour: 45,
        total_value: 0
      }]
    }]);
  };

  const handleDeleteShift = (index) => {
    const currentShifts = Array.isArray(shifts) ? shifts : [];
    onChange(currentShifts.filter((_, i) => i !== index));
  };

  const handleShiftChange = (index, field, value) => {
    const currentShifts = Array.isArray(shifts) ? shifts : [];
    const newShifts = [...currentShifts];
    newShifts[index] = { ...newShifts[index], [field]: value };
    onChange(newShifts);
  };

  const handleRolesChange = (shiftIndex, roles) => {
    const currentShifts = Array.isArray(shifts) ? shifts : [];
    const newShifts = [...currentShifts];
    newShifts[shiftIndex] = { ...newShifts[shiftIndex], roles };
    onChange(newShifts);
  };

  const handleAddonToggle = (addon, checked) => {
    const currentAddons = addons || {};
    onAddonsChange({
      ...currentAddons,
      [addon]: typeof currentAddons[addon] === 'object' 
        ? { ...currentAddons[addon], enabled: checked }
        : checked
    });
  };

  const handleAddonTextChange = (addon, text) => {
    const currentAddons = addons || {};
    onAddonsChange({
      ...currentAddons,
      [addon]: { ...currentAddons[addon], text }
    });
  };

  const safeShifts = Array.isArray(shifts) ? shifts : [];
  const safeAddons = addons || {
    goal: { enabled: false, text: "" },
    portal_access: false,
    meal_provided: false,
    travel_time: false,
    tips: { enabled: false, amount: "300/300" }
  };

  return (
    <div className="space-y-6">
      {safeShifts.map((shift, shiftIndex) => {
        const safeShift = shift || {};
        const safeRoles = Array.isArray(safeShift.roles) ? safeShift.roles : [];
        
        return (
          <Card key={shiftIndex} className="border-2 border-slate-200 shadow-md">
            <CardContent className="p-6">
              {/* Shift Header */}
              <div className="flex items-start justify-between mb-6 pb-4 border-b border-slate-200">
                <div className="flex items-center gap-3 flex-1">
                  <div className="w-12 h-12 bg-gradient-to-br from-purple-500 to-pink-500 rounded-xl flex items-center justify-center text-white font-bold text-lg shadow-lg">
                    {shiftIndex + 1}
                  </div>
                  <div className="flex-1">
                    <Input
                      value={safeShift.shift_name || ""}
                      onChange={(e) => handleShiftChange(shiftIndex, 'shift_name', e.target.value)}
                      className="font-bold text-lg border-none p-0 h-auto focus-visible:ring-0 mb-2"
                      placeholder="Shift Name"
                    />
                    <div className="flex items-center gap-2 text-sm text-slate-500">
                      <MapPin className="w-4 h-4 flex-shrink-0" />
                      <Input
                        value={safeShift.location_address || ""}
                        onChange={(e) => handleShiftChange(shiftIndex, 'location_address', e.target.value)}
                        placeholder="1234 Elm Street, Apt 56B, Springfield, IL 62704, USA"
                        className="border-none p-0 h-auto text-sm focus-visible:ring-0 text-slate-600"
                      />
                    </div>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="border-slate-300"
                  >
                    <Users className="w-4 h-4 mr-2" />
                    Add shift contact
                  </Button>
                  {safeShifts.length > 1 && (
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => handleDeleteShift(shiftIndex)}
                      className="border-red-300 text-red-600 hover:bg-red-50"
                    >
                      <Trash2 className="w-4 h-4 mr-2" />
                      Delete Shift
                    </Button>
                  )}
                </div>
              </div>

              {/* Roles as Cards */}
              <div className="space-y-4">
                {safeRoles.map((role, roleIndex) => (
                  <ShiftRoleCard
                    key={roleIndex}
                    role={role || {}}
                    roleIndex={roleIndex}
                    selectedVendor={selectedVendor}
                    onRoleChange={(field, value) => {
                      const newRoles = [...safeRoles];
                      newRoles[roleIndex] = { ...newRoles[roleIndex], [field]: value };
                      
                      // Calculate hours if times changed
                      if (field === 'start_time' || field === 'end_time') {
                        const start = newRoles[roleIndex].start_time;
                        const end = newRoles[roleIndex].end_time;
                        const hours = calculateHours(start, end);
                        newRoles[roleIndex].hours = hours;
                      }
                      
                      // Calculate total value
                      const count = newRoles[roleIndex].count || 0;
                      const hours = newRoles[roleIndex].hours || 0;
                      const cost = newRoles[roleIndex].cost_per_hour || 0;
                      newRoles[roleIndex].total_value = count * hours * cost;
                      
                      handleRolesChange(shiftIndex, newRoles);
                    }}
                    onDelete={() => {
                      const newRoles = safeRoles.filter((_, i) => i !== roleIndex);
                      handleRolesChange(shiftIndex, newRoles);
                    }}
                    canDelete={safeRoles.length > 1}
                  />
                ))}
              </div>

              {/* Add Role Button */}
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  const newRoles = [...safeRoles, {
                    role: "",
                    department: "",
                    count: 1,
                    start_time: "12:00 PM",
                    end_time: "05:00 PM",
                    hours: 5,
                    uniform: "Type 1",
                    break_minutes: 30,
                    cost_per_hour: 45,
                    total_value: 0
                  }];
                  handleRolesChange(shiftIndex, newRoles);
                }}
                className="w-full mt-4 border-dashed border-2 border-slate-300 hover:border-[#0A39DF] hover:text-[#0A39DF] hover:bg-blue-50"
              >
                <Plus className="w-4 h-4 mr-2" />
                Add Role
              </Button>

              {/* Shift Total */}
              <div className="mt-6 pt-4 border-t border-slate-200 flex items-center justify-between">
                <span className="text-sm font-semibold text-slate-600">Shift Total:</span>
                <span className="text-2xl font-bold text-[#0A39DF]">
                  ${safeRoles.reduce((sum, r) => sum + ((r && r.total_value) || 0), 0).toFixed(2)}
                </span>
              </div>
            </CardContent>
          </Card>
        );
      })}

      {/* Add Location/Shift Button */}
      <Button
        type="button"
        variant="outline"
        onClick={handleAddShift}
        className="w-full h-16 border-2 border-dashed border-slate-300 hover:border-[#0A39DF] hover:text-[#0A39DF] hover:bg-blue-50 text-base font-semibold"
      >
        <Plus className="w-5 h-5 mr-2" />
        Add Another Location / Shift
      </Button>

      {/* Other Addons */}
      <Card className="border-slate-200 shadow-md">
        <CardContent className="p-6">
          <h3 className="text-lg font-bold text-slate-900 mb-6">Other Addons</h3>
          
          <div className="space-y-4">
            {/* Goal */}
            <div className="flex items-center justify-between">
              <Label className="text-sm text-slate-700">Goal</Label>
              <div className="flex items-center gap-3">
                <Switch
                  checked={safeAddons.goal?.enabled || false}
                  onCheckedChange={(checked) => handleAddonToggle('goal', checked)}
                  className="data-[state=checked]:bg-green-500"
                />
                {safeAddons.goal?.enabled && (
                  <Input
                    value={safeAddons.goal?.text || ""}
                    onChange={(e) => handleAddonTextChange('goal', e.target.value)}
                    placeholder="Enter goal"
                    className="w-64"
                  />
                )}
              </div>
            </div>

            {/* Portal Access */}
            <div className="flex items-center justify-between">
              <Label className="text-sm text-slate-700">Portal Access</Label>
              <Switch
                checked={safeAddons.portal_access || false}
                onCheckedChange={(checked) => handleAddonToggle('portal_access', checked)}
                className="data-[state=checked]:bg-green-500"
              />
            </div>

            {/* Meal Provided */}
            <div className="flex items-center justify-between">
              <Label className="text-sm text-slate-700">Meal Provided</Label>
              <Switch
                checked={safeAddons.meal_provided || false}
                onCheckedChange={(checked) => handleAddonToggle('meal_provided', checked)}
                className="data-[state=checked]:bg-green-500"
              />
            </div>

            {/* Travel Time */}
            <div className="flex items-center justify-between">
              <Label className="text-sm text-slate-700">Travel Time</Label>
              <Switch
                checked={safeAddons.travel_time || false}
                onCheckedChange={(checked) => handleAddonToggle('travel_time', checked)}
                className="data-[state=checked]:bg-green-500"
              />
            </div>

            {/* Tips */}
            <div className="flex items-center justify-between">
              <Label className="text-sm text-slate-700">Tips</Label>
              <div className="flex items-center gap-3">
                <Switch
                  checked={safeAddons.tips?.enabled || false}
                  onCheckedChange={(checked) => handleAddonToggle('tips', checked)}
                  className="data-[state=checked]:bg-green-500"
                />
                {safeAddons.tips?.enabled && (
                  <Input
                    value={safeAddons.tips?.amount || ""}
                    onChange={(e) => handleAddonTextChange('tips', e.target.value)}
                    placeholder="300/300"
                    className="w-24 text-center"
                  />
                )}
              </div>
            </div>

            {/* Comments */}
            <div>
              <Label className="text-sm text-slate-700 mb-2 block">Comments</Label>
              <Textarea
                placeholder="Add your main text here..."
                rows={3}
                className="resize-none"
              />
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function calculateHours(start, end) {
  if (!start || !end) return 0;
  const startHour = parseInt(start.split(':')[0]) + (start.includes('PM') && !start.startsWith('12') ? 12 : 0);
  const endHour = parseInt(end.split(':')[0]) + (end.includes('PM') && !end.startsWith('12') ? 12 : 0);
  return Math.max(0, endHour - startHour);
}