"use client";

import React, { useState } 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 { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { ASSET_TYPES, MARKETS } from "@/lib/utils";
import { Upload, X, FileText, Loader2, AlertCircle } from "lucide-react";
import { useToast } from "@/components/ui/toast";

export function SellerForm() {
  const router = useRouter();
  const { addToast } = useToast();
  const [loading, setLoading] = useState(false);
  const [files, setFiles] = useState<File[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formData, setFormData] = useState({
    address: "",
    asset_type: "",
    asking_price: "",
    cap_rate: "",
    noi: "",
    sqft: "",
    units: "",
    year_built: "",
    market: "",
    notes: "",
  });

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      setFiles((prev) => [...prev, ...Array.from(e.target.files!)]);
    }
  };

  const removeFile = (index: number) => {
    setFiles((prev) => prev.filter((_, i) => i !== index));
  };

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};
    if (!formData.address.trim()) newErrors.address = "Property address is required";
    if (!formData.asset_type) newErrors.asset_type = "Select an asset type";
    if (!formData.asking_price) newErrors.asking_price = "Asking price is required";
    if (!formData.market) newErrors.market = "Select a market";
    if (formData.asking_price && Number(formData.asking_price) <= 0) newErrors.asking_price = "Price must be positive";
    if (formData.cap_rate && (Number(formData.cap_rate) < 0 || Number(formData.cap_rate) > 20)) newErrors.cap_rate = "Cap rate must be 0-20%";
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) {
      addToast({ type: "error", title: "Validation Error", description: "Please fix the highlighted fields." });
      return;
    }
    setLoading(true);

    try {
      const res = await fetch('/api/sellers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          address: formData.address,
          asset_type: formData.asset_type,
          asking_price: formData.asking_price ? parseFloat(formData.asking_price) : null,
          cap_rate: formData.cap_rate ? parseFloat(formData.cap_rate) : null,
          noi: formData.noi ? parseFloat(formData.noi) : null,
          sqft: formData.sqft ? parseInt(formData.sqft) : null,
          units: formData.units ? parseInt(formData.units) : null,
          year_built: formData.year_built ? parseInt(formData.year_built) : null,
          market: formData.market,
          notes: formData.notes || null,
        }),
      });

      if (res.ok) {
        const lead = await res.json();
        // Trigger matching engine in background
        fetch('/api/matches/run', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ lead_id: lead.id }),
        }).catch(() => {});

        addToast({
          type: "success",
          title: "Seller Lead Created!",
          description: `${formData.address} has been added. Matching engine triggered.`,
          duration: 5000,
        });

        router.push("/dashboard/sellers");
      } else {
        const err = await res.json();
        addToast({ type: "error", title: "Error", description: err.error || "Failed to create lead." });
      }
    } catch {
      addToast({ type: "error", title: "Error", description: "Failed to create lead. Please try again." });
    }

    setLoading(false);
  };

  const fieldError = (field: string) =>
    errors[field] ? (
      <p className="flex items-center gap-1 text-xs text-red-600 mt-1">
        <AlertCircle className="h-3 w-3" />
        {errors[field]}
      </p>
    ) : null;

  return (
    <form onSubmit={handleSubmit}>
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 animate-page-in">
        {/* Main form */}
        <div className="lg:col-span-2 space-y-6">
          {/* Property Details */}
          <Card className="hover-lift">
            <CardHeader>
              <CardTitle className="text-lg">Property Details</CardTitle>
              <CardDescription>Enter the key details about the seller&apos;s property</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="address">Property Address *</Label>
                <Input
                  id="address"
                  placeholder="123 Main St, Suite 100"
                  value={formData.address}
                  onChange={(e) => handleChange("address", e.target.value)}
                  className={`mt-1.5 ${errors.address ? "border-red-400 focus:ring-red-400" : ""}`}
                />
                {fieldError("address")}
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="asset_type">Asset Type *</Label>
                  <Select
                    value={formData.asset_type}
                    onValueChange={(v) => handleChange("asset_type", v)}
                  >
                    <SelectTrigger className={`mt-1.5 ${errors.asset_type ? "border-red-400" : ""}`}>
                      <SelectValue placeholder="Select type" />
                    </SelectTrigger>
                    <SelectContent>
                      {ASSET_TYPES.map((type) => (
                        <SelectItem key={type} value={type}>
                          {type}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {fieldError("asset_type")}
                </div>
                <div>
                  <Label htmlFor="market">Market / Location *</Label>
                  <Select
                    value={formData.market}
                    onValueChange={(v) => handleChange("market", v)}
                  >
                    <SelectTrigger className={`mt-1.5 ${errors.market ? "border-red-400" : ""}`}>
                      <SelectValue placeholder="Select market" />
                    </SelectTrigger>
                    <SelectContent>
                      {MARKETS.map((market) => (
                        <SelectItem key={market} value={market}>
                          {market}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {fieldError("market")}
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="sqft">Square Footage</Label>
                  <Input
                    id="sqft"
                    type="number"
                    placeholder="50,000"
                    value={formData.sqft}
                    onChange={(e) => handleChange("sqft", e.target.value)}
                    className="mt-1.5"
                  />
                </div>
                <div>
                  <Label htmlFor="units">Units</Label>
                  <Input
                    id="units"
                    type="number"
                    placeholder="120"
                    value={formData.units}
                    onChange={(e) => handleChange("units", e.target.value)}
                    className="mt-1.5"
                  />
                </div>
                <div>
                  <Label htmlFor="year_built">Year Built</Label>
                  <Input
                    id="year_built"
                    type="number"
                    placeholder="2005"
                    value={formData.year_built}
                    onChange={(e) => handleChange("year_built", e.target.value)}
                    className="mt-1.5"
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Financials */}
          <Card className="hover-lift">
            <CardHeader>
              <CardTitle className="text-lg">Financial Details</CardTitle>
              <CardDescription>Pricing and financial metrics for the property</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="asking_price">Asking Price ($) *</Label>
                  <Input
                    id="asking_price"
                    type="number"
                    placeholder="5,000,000"
                    value={formData.asking_price}
                    onChange={(e) => handleChange("asking_price", e.target.value)}
                    className={`mt-1.5 ${errors.asking_price ? "border-red-400" : ""}`}
                  />
                  {fieldError("asking_price")}
                </div>
                <div>
                  <Label htmlFor="cap_rate">Cap Rate (%)</Label>
                  <Input
                    id="cap_rate"
                    type="number"
                    step="0.01"
                    placeholder="6.50"
                    value={formData.cap_rate}
                    onChange={(e) => handleChange("cap_rate", e.target.value)}
                    className={`mt-1.5 ${errors.cap_rate ? "border-red-400" : ""}`}
                  />
                  {fieldError("cap_rate")}
                </div>
                <div>
                  <Label htmlFor="noi">NOI ($)</Label>
                  <Input
                    id="noi"
                    type="number"
                    placeholder="325,000"
                    value={formData.noi}
                    onChange={(e) => handleChange("noi", e.target.value)}
                    className="mt-1.5"
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Notes */}
          <Card className="hover-lift">
            <CardHeader>
              <CardTitle className="text-lg">Additional Notes</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="relative">
                <Textarea
                  placeholder="Any additional details about the property, seller motivation, timeline, etc."
                  value={formData.notes}
                  onChange={(e) => handleChange("notes", e.target.value)}
                  rows={4}
                  maxLength={1000}
                />
                <span className="absolute bottom-2 right-3 text-xs text-navy-400">
                  {formData.notes.length}/1000
                </span>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Sidebar - Documents + Submit */}
        <div className="space-y-6">
          <Card className="hover-lift">
            <CardHeader>
              <CardTitle className="text-lg">Documents</CardTitle>
              <CardDescription>Upload OMs, financials, photos</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="border-2 border-dashed border-navy-200 rounded-lg p-6 text-center hover:border-gold-400 transition-colors cursor-pointer">
                <input
                  type="file"
                  multiple
                  onChange={handleFileChange}
                  className="hidden"
                  id="file-upload"
                  accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png"
                />
                <label htmlFor="file-upload" className="cursor-pointer">
                  <Upload className="h-8 w-8 text-navy-400 mx-auto mb-2" />
                  <p className="text-sm font-medium text-navy-700">Drop files here or click</p>
                  <p className="text-xs text-navy-400 mt-1">PDF, DOC, XLS, JPG, PNG</p>
                </label>
              </div>

              {files.length > 0 && (
                <div className="mt-4 space-y-2">
                  {files.map((file, idx) => (
                    <div
                      key={idx}
                      className="flex items-center gap-2 p-2 rounded-lg bg-navy-50"
                    >
                      <FileText className="h-4 w-4 text-navy-500 flex-shrink-0" />
                      <span className="text-xs text-navy-700 truncate flex-1">{file.name}</span>
                      <button
                        type="button"
                        onClick={() => removeFile(idx)}
                        className="text-navy-400 hover:text-red-500 transition-colors"
                      >
                        <X className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          <Card className="glow-gold">
            <CardContent className="pt-6">
              <Button type="submit" variant="gold" className="w-full active:scale-[0.98] transition-transform" size="lg" disabled={loading}>
                {loading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Creating Lead...
                  </>
                ) : (
                  "Create Lead & Match Buyers"
                )}
              </Button>
              <p className="text-xs text-navy-400 text-center mt-3">
                This will save the lead and run the matching engine to find relevant buyers.
              </p>
            </CardContent>
          </Card>
        </div>
      </div>
    </form>
  );
}
