"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useToast } from "@/hooks/use-toast";
import { ArrowLeft } from "lucide-react";
import Link from "next/link";
import { ProtectedLayout } from "@/components/protected-layout";

export default function NewFilePage() {
  const router = useRouter();
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const [agents, setAgents] = useState<any[]>([]);
  const [formData, setFormData] = useState({
    customerName: "",
    phoneNumber: "",
    idNumber: "",
    alias: "",
    appliedAmount: "",
    allocatedAmount: "",
    assignedAgentId: "",
    dateOutsourced: "",
    status: "NEW",
  });

  useEffect(() => {
    fetchAgents();
  }, []);

  const fetchAgents = async () => {
    try {
      const res = await fetch("/api/users?role=AGENT");
      if (res.ok) {
        const data = await res.json();
        setAgents(data?.users ?? []);
      }
    } catch (error) {
      console.error("Error fetching agents:", error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);

    try {
      const res = await fetch("/api/collection-files", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...formData,
          appliedAmount: parseFloat(formData.appliedAmount) || 0,
          allocatedAmount: parseFloat(formData.allocatedAmount) || 0,
        }),
      });

      if (!res.ok) {
        throw new Error("Failed to create file");
      }

      toast({
        title: "Success",
        description: "Collection file created successfully",
      });

      router.push("/files");
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to create collection file",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <ProtectedLayout>
      <div className="p-8">
        <Link href="/files">
          <Button variant="ghost" className="mb-4">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Files
          </Button>
        </Link>

        <Card className="max-w-2xl">
          <CardHeader>
            <CardTitle>Create New Collection File</CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="customerName">Customer Name *</Label>
                  <Input
                    id="customerName"
                    value={formData.customerName}
                    onChange={(e) =>
                      setFormData({ ...formData, customerName: e.target.value })
                    }
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="phoneNumber">Phone Number *</Label>
                  <Input
                    id="phoneNumber"
                    value={formData.phoneNumber}
                    onChange={(e) =>
                      setFormData({ ...formData, phoneNumber: e.target.value })
                    }
                    required
                  />
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="idNumber">ID Number</Label>
                  <Input
                    id="idNumber"
                    value={formData.idNumber}
                    onChange={(e) =>
                      setFormData({ ...formData, idNumber: e.target.value })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="alias">Alias</Label>
                  <Input
                    id="alias"
                    value={formData.alias}
                    onChange={(e) =>
                      setFormData({ ...formData, alias: e.target.value })
                    }
                  />
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="appliedAmount">Applied Amount</Label>
                  <Input
                    id="appliedAmount"
                    type="number"
                    step="0.01"
                    value={formData.appliedAmount}
                    onChange={(e) =>
                      setFormData({ ...formData, appliedAmount: e.target.value })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="allocatedAmount">Allocated Amount</Label>
                  <Input
                    id="allocatedAmount"
                    type="number"
                    step="0.01"
                    value={formData.allocatedAmount}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        allocatedAmount: e.target.value,
                      })
                    }
                  />
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="assignedAgentId">Assigned Agent</Label>
                  <Select
                    value={formData.assignedAgentId}
                    onValueChange={(value) =>
                      setFormData({ ...formData, assignedAgentId: value })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select agent" />
                    </SelectTrigger>
                    <SelectContent>
                      {agents?.map?.((agent) => (
                        <SelectItem key={agent?.id} value={agent?.id ?? ""}>
                          {agent?.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="dateOutsourced">Date Outsourced</Label>
                  <Input
                    id="dateOutsourced"
                    type="date"
                    value={formData.dateOutsourced}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        dateOutsourced: e.target.value,
                      })
                    }
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="status">Status</Label>
                <Select
                  value={formData.status}
                  onValueChange={(value) =>
                    setFormData({ ...formData, status: value })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="NEW">New</SelectItem>
                    <SelectItem value="IN_PROGRESS">In Progress</SelectItem>
                    <SelectItem value="PAID">Paid</SelectItem>
                    <SelectItem value="DEFAULTED">Defaulted</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="flex gap-4 pt-4">
                <Button type="submit" disabled={isLoading} className="flex-1">
                  {isLoading ? "Creating..." : "Create File"}
                </Button>
                <Link href="/files" className="flex-1">
                  <Button type="button" variant="outline" className="w-full">
                    Cancel
                  </Button>
                </Link>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </ProtectedLayout>
  );
}
