import React, { useState } from "react";
import {
  FaUpload,
  FaCheckCircle,
  FaCopy,
  FaExclamationCircle,
  FaArrowLeft,
} from "react-icons/fa";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import Header from "./Header";
import Footer from "./Footer";
import {
  submitComplaint,
  ComplaintPayload,
  FileInfo,
} from "../../shared/services/complaintService";

const ComplaintForm = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();

  const [files, setFiles] = useState<File[]>([]);
  const [loading, setLoading] = useState(false);
  const [disclaimerAccepted, setDisclaimerAccepted] = useState(false);
  const [submissionSuccess, setSubmissionSuccess] = useState(false);
  const [complaintId, setComplaintId] = useState("");
  const [error, setError] = useState<string | null>(null);

  const [formValues, setFormValues] = useState({
    fullName: "",
    subCity: "",
    woreda: "",
    houseNumber: "",
    phone: "",
    institution: "",
    complaintDetails: "",
    complaintWant: "",
    complaintPlace: "",
  });

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    setFormValues({ ...formValues, [e.target.name]: e.target.value });
  };

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!disclaimerAccepted) return;

    setLoading(true);
    setError(null);

    try {
      // Prepare file info if files are uploaded
      let fileInfo: FileInfo | undefined;
      if (files.length > 0) {
        const file = files[0]; // Take the first file for now
        fileInfo = {
          fileName: file.name,
          contentType: file.type,
          size: file.size,
          originalname: file.name,
        };
      }

      // Prepare the complaint payload
      const payload: ComplaintPayload = {
        fullName: formValues.fullName,
        phoneNumber: formValues.phone,
        subCity: formValues.subCity,
        woreda: formValues.woreda,
        houseNumber: formValues.houseNumber,
        institution: formValues.institution,
        complaintPlace: formValues.complaintPlace,
        complaintDetail: formValues.complaintDetails,
        desiredResolution: formValues.complaintWant,
        fileInfo,
      };

      // Submit the complaint
      const response = await submitComplaint(payload);

      if (response.data) {
        setComplaintId(response.data.complaintNumber || response.data.id);
        setSubmissionSuccess(true);
        toast.success(t("complaint.success"));
      }
    } catch (err: any) {
      console.error("Error submitting complaint:", err);
      const errorMessage =
        err.response?.data?.message || err.message || t("complaint.error");
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Header />
      <div className="min-h-screen bg-gradient-to-b from-blue-50 to-white flex flex-col pt-16 md:pt-20">
        {/* Hero Section */}
        <div className="bg-primary py-16 text-center text-white relative overflow-hidden">
          <div className="absolute top-0 left-0 w-full h-full bg-[url('https://www.transparenttextures.com/patterns/cubes.png')] opacity-10"></div>
          <h1 className="text-4xl md:text-5xl font-bold mb-4 relative z-10 animate-fade-in">
            {t("complaint.title")}
          </h1>
          <p className="max-w-2xl mx-auto text-lg opacity-90 relative z-10">
            {t("complaint.subtitle")}
          </p>
        </div>

        {/* Main Form */}
        <div className="flex-1 flex justify-center p-6">
          <div className="w-full max-w-3xl bg-white shadow-2xl rounded-2xl p-8 relative border border-gray-100">
            {/* Floating circles */}
            <div className="absolute -top-6 -left-6 w-16 h-16 bg-blue-100 rounded-full opacity-30 animate-pulse"></div>
            <div className="absolute -bottom-6 -right-6 w-24 h-24 bg-blue-100 rounded-full opacity-30 animate-ping"></div>

            <h2 className="text-2xl font-semibold text-blue-800 mb-8 text-center">
              {t("complaint.formTitle")}
            </h2>

            {error && (
              <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
                <div className="flex items-center gap-2">
                  <FaExclamationCircle className="text-red-500" />
                  <span className="text-red-700 font-medium">
                    {t("complaint.error")}
                  </span>
                </div>
                <p className="text-red-600 text-sm mt-1">{error}</p>
              </div>
            )}

            {submissionSuccess ? (
              <div className="text-center animate-fade-in">
                <FaCheckCircle className="text-primary-500 text-5xl mx-auto mb-4" />
                <h3 className="text-xl font-semibold mb-2">
                  {t("complaint.success")}
                </h3>
                <p className="mb-4 text-gray-600">{t("complaint.keepId")}</p>
                <div className="bg-gray-100 border rounded-lg p-4 flex justify-center items-center gap-3">
                  <span className="font-bold text-blue-700">{complaintId}</span>
                  <button
                    className="p-2 rounded hover:bg-gray-200"
                    onClick={() => navigator.clipboard.writeText(complaintId)}
                  >
                    <FaCopy />
                  </button>
                </div>
                <div className="flex justify-center gap-4 mt-6">
                  <button
                    onClick={() => setSubmissionSuccess(false)}
                    className="px-6 py-3 bg-primary text-primary-foreground rounded-lg shadow hover:bg-primary/90 transition"
                  >
                    {t("complaint.close")}
                  </button>
                  <button
                    onClick={() => navigate("/complaints")}
                    className="px-6 py-3 bg-gray-300 text-gray-800 rounded-lg shadow hover:bg-gray-400 transition flex items-center gap-2"
                  >
                    <FaArrowLeft /> {t("complaint.back")}
                  </button>
                </div>
              </div>
            ) : (
              <form
                onSubmit={handleSubmit}
                className="space-y-6 animate-fade-in"
              >
                {/* Inputs */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <input
                    type="text"
                    name="fullName"
                    value={formValues.fullName}
                    onChange={handleChange}
                    placeholder={t("complaint.fullName")}
                    required
                    className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none"
                  />
                  <input
                    type="tel"
                    name="phone"
                    value={formValues.phone}
                    onChange={handleChange}
                    placeholder={t("complaint.phone")}
                    required
                    className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none"
                  />
                  <input
                    type="text"
                    name="subCity"
                    value={formValues.subCity}
                    onChange={handleChange}
                    placeholder={t("complaint.subCity")}
                    className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none"
                  />
                  <input
                    type="text"
                    name="woreda"
                    value={formValues.woreda}
                    onChange={handleChange}
                    placeholder={t("complaint.woreda")}
                    className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none"
                  />
                  <input
                    type="text"
                    name="houseNumber"
                    value={formValues.houseNumber}
                    onChange={handleChange}
                    placeholder={t("complaint.houseNumber")}
                    className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none"
                  />
                  <input
                    type="text"
                    name="institution"
                    value={formValues.institution}
                    onChange={handleChange}
                    placeholder={t("complaint.institution")}
                    className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none"
                  />
                </div>

                <input
                  type="text"
                  name="complaintPlace"
                  value={formValues.complaintPlace}
                  onChange={handleChange}
                  placeholder={t("complaint.place")}
                  className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none"
                />

                <textarea
                  name="complaintDetails"
                  value={formValues.complaintDetails}
                  onChange={handleChange}
                  placeholder={t("complaint.details")}
                  rows={4}
                  className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none"
                ></textarea>

                <textarea
                  name="complaintWant"
                  value={formValues.complaintWant}
                  onChange={handleChange}
                  placeholder={t("complaint.want")}
                  rows={4}
                  className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none"
                ></textarea>

                {/* File Upload */}
                {/* <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t("complaint.evidence")}
                  </label>
                  <div className="flex items-center gap-3">
                    <input
                      type="file"
                      multiple
                      onChange={handleFileChange}
                      className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4
                               file:rounded-lg file:border-0
                               file:text-sm file:font-semibold
                               file:bg-blue-50 file:text-blue-700
                               hover:file:bg-blue-100"
                    />
                    <FaUpload className="text-gray-400" />
                  </div>
                  {files.length > 0 && (
                    <p className="text-sm text-gray-500 mt-2">
                      {t("complaint.selectedFiles")}:{" "}
                      {files.map((f) => f.name).join(", ")}
                    </p>
                  )}
                </div> */}

                {/* Disclaimer */}
                <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <FaExclamationCircle className="text-red-500" />
                    <span className="font-semibold text-red-700">
                      {t("complaint.disclaimerTitle")}
                    </span>
                  </div>
                  <p className="text-sm text-gray-700">
                    {t("complaint.disclaimerText")}
                  </p>
                </div>

                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={disclaimerAccepted}
                    onChange={(e) => setDisclaimerAccepted(e.target.checked)}
                    className="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary"
                  />
                  <span className="text-sm text-gray-700">
                    {t("complaint.accept")}
                  </span>
                </div>

                {/* Submit + Back */}
                <div className="flex justify-between items-center gap-4">
                  <button
                    type="button"
                    onClick={() => navigate("/complaints")}
                    className="flex items-center gap-2 px-5 py-3 bg-gray-300 text-gray-800 rounded-lg shadow hover:bg-gray-400 transition"
                  >
                    <FaArrowLeft /> {t("complaint.back")}
                  </button>
                  <button
                    type="submit"
                    disabled={!disclaimerAccepted || loading}
                    className={`px-6 py-3 rounded-lg text-white font-semibold transition flex items-center justify-center gap-2
                  ${
                    loading || !disclaimerAccepted
                      ? "bg-gray-400 cursor-not-allowed"
                      : "bg-primary hover:bg-primary-700"
                  }`}
                  >
                    {loading && (
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                    )}
                    {loading
                      ? t("complaint.submitting")
                      : t("complaint.submit")}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default ComplaintForm;
